package com.shuangseqiu.service.impl;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * HTTP服务，用于处理网页内容获取
 */
@Component
public class HttpService {

    private static final Logger logger = LoggerFactory.getLogger(HttpService.class);
    private CloseableHttpClient httpClient;

    /**
     * 初始化HttpClient
     */
    @PostConstruct
    public void init() {
        // 创建HttpClient实例
        this.httpClient = HttpClients.custom()
                .setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36")
                .build();
        logger.info("HttpClient已初始化完成");
    }

    /**
     * 获取网页内容
     *
     * @param url 要访问的网址
     * @return 网页HTML内容
     */
    public String getPageContent(String url) {
        try {
            HttpGet request = new HttpGet(url);
            request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
            request.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
            request.addHeader("Accept-Encoding", "gzip, deflate");
            request.addHeader("Connection", "keep-alive");
            
            HttpResponse response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();
            
            if (entity != null) {
                String content = EntityUtils.toString(entity, "UTF-8");
                logger.info("成功获取网页内容，长度: {} 字符", content.length());
                return content;
            }
        } catch (Exception e) {
            logger.error("获取网页内容失败: {}", url, e);
            throw new RuntimeException("获取网页内容失败", e);
        }
        return "";
    }

    /**
     * 关闭HttpClient资源
     */
    @PreDestroy
    public void cleanup() {
        try {
            if (httpClient != null) {
                httpClient.close();
                logger.info("HttpClient资源已关闭");
            }
        } catch (IOException e) {
            logger.error("关闭HttpClient失败", e);
        }
    }
}